package com.insigma.business.qrcode.soldier.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.google.common.collect.Lists;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Slf4j
@Component
public class PdfService {

    @Value("${sm.tmp.dir}")
    private String tmpDir = "D:\\";

    public String fillTemplatePdf(String templateUrl, Map<String, String> kv, Map<String, String> imgKv) throws IOException, DocumentException {
        log.info("pdf模板填充，{}，{}，{}", templateUrl, kv, imgKv);
        URL source = new URL(templateUrl);
        InputStream inputStream = source.openStream();
        PdfReader reader = new PdfReader(inputStream);
        String pdfName = System.currentTimeMillis() + ".pdf";
        String targetPath = tmpDir + pdfName;
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(targetPath));
        AcroFields form = stamper.getAcroFields();

        if (kv != null) {
            for (Map.Entry<String, String> entry : kv.entrySet()) {
                form.setField(entry.getKey(), entry.getValue());
            }
        }

        if (imgKv != null) {
            for (Map.Entry<String, String> entry : imgKv.entrySet()) {
                String fieldName = entry.getKey();
                int pageNo = form.getFieldPositions(fieldName).get(0).page;
                Rectangle signRect = form.getFieldPositions(fieldName).get(0).position;
                float x = signRect.getLeft();
                float y = signRect.getBottom();

                
                Image image = Image.getInstance(new URL(entry.getValue()));
                
                PdfContentByte under = stamper.getOverContent(pageNo);
                
                image.scaleToFit(signRect.getWidth(), signRect.getHeight());
                
                image.setAbsolutePosition(x, y);
                under.addImage(image);
            }

        }
        stamper.close();
        reader.close();
        String yyyMMdd = DateUtil.formatDate(new Date());
        String objectKey = "prod/pdf/" + yyyMMdd + "/" + pdfName;
        File file = new File(targetPath);
        String target = OssUtil.saveFile(file, objectKey);
        file.delete();
        return target;
    }

    public byte[] fillTemplatePdfToByte(String templateUrl, Map<String, String> kv, Map<String, String> imgKv) throws IOException, DocumentException {
        log.info("pdf模板填充，{}，{}，{}", templateUrl, kv, imgKv);
        URL source = new URL(templateUrl);
        InputStream inputStream = source.openStream();
        PdfReader reader = new PdfReader(inputStream);
        String pdfName = System.currentTimeMillis() + ".pdf";
        String targetPath = tmpDir + pdfName;
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(targetPath));
        AcroFields form = stamper.getAcroFields();

        if (kv != null) {
            for (Map.Entry<String, String> entry : kv.entrySet()) {
                form.setField(entry.getKey(), entry.getValue());
            }
        }

        if (imgKv != null) {
            for (Map.Entry<String, String> entry : imgKv.entrySet()) {
                String fieldName = entry.getKey();
                int pageNo = form.getFieldPositions(fieldName).get(0).page;
                Rectangle signRect = form.getFieldPositions(fieldName).get(0).position;
                float x = signRect.getLeft();
                float y = signRect.getBottom();

                
                Image image = Image.getInstance(new URL(entry.getValue()));
                
                PdfContentByte under = stamper.getOverContent(pageNo);
                
                image.scaleToFit(signRect.getWidth(), signRect.getHeight());
                
                image.setAbsolutePosition(x, y);
                under.addImage(image);
            }

        }
        stamper.close();
        reader.close();

        File file = new File(targetPath);

        byte[] bytesArray = new byte[(int) file.length()];
        FileInputStream fis = new FileInputStream(file);
        fis.read(bytesArray); 
        fis.close();
        file.delete();
        return bytesArray;
    }

    public static void main(String[] args) throws IOException, DocumentException {
        byte[] bytes = FileUtil.readBytes("E:\\download\\王良杰.pdf");
        byte[] bytes1 = FileUtil.readBytes("E:\\download\\寇晓东.pdf");
        byte[] bytes2 = FileUtil.readBytes("E:\\download\\魏功辉.pdf");

        byte[] mergepdf = new PdfService().mergepdf(Lists.newArrayList(bytes, bytes1, bytes2));





    }

    private static void addImgToPdf() throws IOException, DocumentException {
        
        String templatePath = "C:\\Users\\jin\\Desktop\\44.pdf";
        
        String newPDFPath = "d:\\shouju_fb3.pdf";
        
        String fieldName = "f1";
        
        String imagePath = "C:\\Users\\jin\\Desktop\\ui\\aa.png";

        
        InputStream input = new FileInputStream(new File(templatePath));
        PdfReader reader = new PdfReader(input);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(newPDFPath));
        
        AcroFields form = stamper.getAcroFields();


        form.setField("f2", "abc");

        
        int pageNo = form.getFieldPositions(fieldName).get(0).page;
        Rectangle signRect = form.getFieldPositions(fieldName).get(0).position;
        float x = signRect.getLeft();
        float y = signRect.getBottom();

        
        Image image = Image.getInstance(imagePath);
        
        PdfContentByte under = stamper.getOverContent(pageNo);
        
        image.scaleToFit(signRect.getWidth(), signRect.getHeight());
        
        image.setAbsolutePosition(x, y);
        under.addImage(image);
        stamper.close();
        reader.close();
    }

    public byte[] mergepdf(List<byte[]> fileList) {
        Document document = null;
        String savepath = null;
        try {
            savepath = tmpDir + System.currentTimeMillis() + ".pdf";
            document = new Document(new PdfReader(fileList.get(0)).getPageSize(1));
            FileOutputStream os = new FileOutputStream(savepath);
            PdfCopy copy = new PdfCopy(document, os);

            document.open();
            for (int i = 0; i < fileList.size(); i++) {
                PdfReader reader = new PdfReader(fileList.get(i));
                copy.addDocument(reader);
                reader.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (DocumentException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (document != null) {
                document.close();
            }
        }

        byte[] bytes = FileUtil.readBytes(savepath);
        FileUtil.del(savepath);
        return bytes;
    }


}
